﻿using HomagChina.Basic.CCT.Db.CCHS_Db;
using HomagChina.Basic.CCT.Db.CCT_Db;
using HomagChina.Basic.CCT.Tools;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Telerik.Windows.Data;
using LocalText = Proxy.Properties.Resources;

namespace Proxy
{
    public class InsertInfoHandle
    {
        private CommonHandle Handle_Common;

        public InsertInfoHandle()
        {
            Handle_Common = new CommonHandle();
        }

        public bool InsertSettingsHandle(T_MachineInfo t)
        {
            bool result = false;
            try
            {
                using (Db_CCT Db = new Db_CCT())
                {
                    Db.T_MachineInfo.Add(t);
                    result = Db.SaveChanges() > 0;
                }
                return result;
            }
            catch (Exception ex)
            {
                return result;
            }
        }

        public bool InsertLibraryConfigHandle(T_CCHS_Position t)
        {
            bool result = false;
            try
            {
                using (Db_CCHS Db = new Db_CCHS())
                {
                    Db.T_CCHS_Position.Add(t);
                    result = Db.SaveChanges() > 0;
                }
                return result;
            }
            catch (Exception ex)
            {
                return result;
            }
        }


        public Returnstructure InsertBoardInfo(BoardlibraryModel m)
        {
            try
            {
                using (var Db = new Db_CCHS())
                {
                    var IsExist = Db.T_CCHS_Boardlibrary.FirstOrDefault(s => s.Boardcode.Equals(m.Boardcode)) == null ? false : true;
                    if (IsExist)
                    {
                        return new Returnstructure() { Code = 2, Msg = "当前数据已存在!" };
                    }
                    else
                    {
                        T_CCHS_Boardlibrary t = Handle_Common.Mapper(new T_CCHS_Boardlibrary(), m);
                        Db.T_CCHS_Boardlibrary.Add(t);
                        return Db.SaveChanges() > 0 ? new Returnstructure() { Code = 1, Msg = "数据添加成功!" }
                                                    : new Returnstructure() { Code = -1, Msg = "数据添加失败!" };
                    }
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
                return new Returnstructure()
                {
                    Code = -1,
                    Msg = ex.Message
                };
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="List_m"></param>
        /// <returns></returns>
        public bool InsertBoardsInfo(List<BoardInfoConstruct> List_t, ObservableCollection<object> List_r)
        {
            DateTime date = DateTime.Now;
            List<T_CCHS_Boardlibrary> list = new List<T_CCHS_Boardlibrary>();
            try
            {
                using (var Db = new Db_CCHS())
                {
                    if (List_r != null)
                    {
                        foreach (var item in List_r)
                        {
                            T_CCHS_Boardlibrary t = Handle_Common.Mapper(new T_CCHS_Boardlibrary(), item);
                            Db.T_CCHS_Boardlibrary.Remove(Db.T_CCHS_Boardlibrary.FirstOrDefault(s => s.Boardcode.Equals(t.Boardcode)));
                        }
                    }

                    foreach (var item in List_t)
                    {
                        T_CCHS_Boardlibrary t = Handle_Common.Mapper(new T_CCHS_Boardlibrary(), item);
                        t.CreationDate = date;
                        list.Add(t);
                    }

                    Db.T_CCHS_Boardlibrary.AddRange(list);
                    return Db.SaveChanges() > 0;
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 导入数据拆解成job和对应的task
        /// </summary>
        /// <param name="stackInfoConstruct"></param>
        /// <param name="TargetPosition"></param>
        /// <returns></returns>
        public Returnstructure InsertJobInfo(StackInfoConstruct stackInfoConstruct, object TargetPosition)
        {
            DateTime date = DateTime.Now;
            T_CCHS_JobList t_CCHS_JobList;
            T_CCHS_TaskDetail t_CCHS_TaskDetail;
            List<T_CCHS_TaskDetail> t_CCHS_TaskDetails = new List<T_CCHS_TaskDetail>();
            List<T_CCHS_StackDetail> list_Detail = new List<T_CCHS_StackDetail>();
            List<TaskInfoContruct> list_tasks = new List<TaskInfoContruct>();
            try
            {
                using (Db_CCHS Db = new Db_CCHS())
                {
                    //查看当前任务是否存在
                    var DuplicateJobDatas = Db.T_CCHS_JobList.Where(s => s.JobId.Equals(stackInfoConstruct.stackInfo.JobId)
                                                                    && s.StackId.Equals(stackInfoConstruct.stackInfo.StackId) && s.State != 30).ToList();
                    if (DuplicateJobDatas.Count() > 0)
                    {
                        return new Returnstructure() { Code = -1, Msg = Utility.GetLocalText("RepetitiousInfo") };
                    }

                    //开始生成任务
                    //单色堆垛
                    if (stackInfoConstruct.stackInfo.IsRainbow.Equals(0))
                    {
                        //查看需要多少原材料
                        var material = stackInfoConstruct.stackDetails[1].Material;
                        var Nq = stackInfoConstruct.stackDetails.Sum(s => s.BoardQuantity);
                        var Aq = Db.T_CCHS_Stock.Where(s => s.Material.Equals(material)).Sum(s => s.ActualQuantity);
                        var Eq = Aq - Db.T_CCHS_TaskDetail.Where(s => s.Material.Equals(material)).Count();

                        if (Nq > Eq)
                        {
                            return new Returnstructure() { Code = -1, Msg = "物料:" + material + " - 当前可用数量为:" + Eq + " - 不满足该工单所需数量!" };
                        }

                        //获取当前排序
                        var sort = Db.T_CCHS_JobList.OrderByDescending(s => s.Sort).FirstOrDefault().Sort;

                        //生成出库任务 Job
                        t_CCHS_JobList = new T_CCHS_JobList()
                        {
                            JobId = stackInfoConstruct.stackInfo.JobId,
                            StackId = stackInfoConstruct.stackInfo.StackId,
                            Material = material,
                            JobType = 1,//出库任务
                            TargetType = 1,
                            TaskQuantity = Nq,
                            TargetPosition = TargetPosition.ToString(),
                            State = 10,
                            CreationDate = date,
                            Sort = sort + 1
                        };

                        Db.T_CCHS_JobList.Add(t_CCHS_JobList);

                        //生成垫板任务 //1.找到垫板库存信息
                        t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                        {
                            JobId = stackInfoConstruct.stackInfo.JobId,
                            StackId = stackInfoConstruct.stackInfo.StackId,
                            StackType = 1,
                            Material = material,
                            Boardcode = stackInfoConstruct.stackDetails[0].Boardcode,
                            BoardType = 0,//垫板
                            Layer = 1,
                            TargetPosition = TargetPosition.ToString(),
                            Orientation = 0,
                            Tasktype = 1,
                            TransferState = 10,
                            CreationDate = date,
                        };
                        t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);

                        var layer = 2;
                        for (int i = 1; i <= stackInfoConstruct.stackDetails.Count - 1; i++)
                        {
                            for (int j = 1; j <= stackInfoConstruct.stackDetails[i].BoardQuantity; j++)
                            {
                                t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                                {
                                    JobId = stackInfoConstruct.stackInfo.JobId,
                                    StackId = stackInfoConstruct.stackInfo.StackId,
                                    StackType = 1,
                                    Material = material,
                                    Boardcode = stackInfoConstruct.stackDetails[i].Boardcode,
                                    BoardType = 1,//原材料 2=余料
                                    TargetPosition = TargetPosition.ToString(),
                                    Layer = layer,
                                    Orientation = stackInfoConstruct.stackDetails[i].Orientation,
                                    Tasktype = 1,
                                    TransferState = 10,
                                    CreationDate = date,
                                };
                                layer++;
                                t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);
                            }
                        }
                        Db.T_CCHS_TaskDetail.AddRange(t_CCHS_TaskDetails);
                        goto CreateJob;
                    }
                    else
                    {
                        //查看当前需要多少中物料
                        var materials = stackInfoConstruct.stackDetails.GroupBy(s => s.Material).ToList();

                        foreach (var material in materials)
                        {
                            // 查看需要多少原材料
                            if (material.Key.Contains("垫板"))
                            {
                                continue;
                            }
                            var Nq = stackInfoConstruct.stackDetails.Where(s => s.Material.Equals(material.Key)).Sum(s => s.BoardQuantity);
                            //确认库存内是否存在足够量的原材料
                            var Aq = Db.T_CCHS_Stock.Where(s => s.Material.Equals(material.Key)).Sum(s => s.ActualQuantity) ?? 0;
                            var Eq = Aq - Db.T_CCHS_TaskDetail.Where(s => s.Material.Equals(material.Key) && s.TransferState != 30).Count();
                            if (Nq > Eq)
                            {
                                return new Returnstructure() { Code = -1, Msg = "物料:" + material.Key + "-当前可用数量为:" + Eq + "-不满足该工单所需数量!" };
                            }
                        }

                        var sourcePosition = new Dictionary<string, int>();
                        int calculatedPcs = 0;

                        var layer = 0;

                        //获取当前排序
                        var sortInfo_1 = Db.T_CCHS_JobList.OrderByDescending(s => s.Sort).FirstOrDefault();
                        var sort_1 = 0;
                        if (sortInfo_1 == null)
                        {
                            sort_1 = 0;
                        }
                        else
                        {
                            sort_1 = (int)sortInfo_1.Sort;
                        }

                        //生成出库任务 Job
                        t_CCHS_JobList = new T_CCHS_JobList()
                        {
                            JobId = stackInfoConstruct.stackInfo.JobId,
                            StackId = stackInfoConstruct.stackInfo.StackId,
                            Material = "Rainbow",
                            JobType = 1,//出库任务
                            TargetType = 1,
                            TaskQuantity = stackInfoConstruct.stackDetails.Sum(s => s.BoardQuantity),
                            TargetPosition = TargetPosition.ToString(),
                            State = 10,
                            CreationDate = date,
                            Sort = sort_1 + 1
                        };

                        //如果是出库任务到出库口
                        if (TargetPosition.ToString().Contains("Outfeed"))
                        {
                            var dummyBoard = Db.T_CCHS_Stock.FirstOrDefault(s => s.Material.Equals("垫板")).Positioncode;
                            //生成垫板任务 //1.找到垫板库存信息
                            t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                            {
                                JobId = stackInfoConstruct.stackInfo.JobId,
                                StackId = stackInfoConstruct.stackInfo.StackId,
                                StackType = 1,
                                Material = "垫板",
                                Boardcode = stackInfoConstruct.stackDetails[0].Boardcode,
                                BoardType = 0,//垫板
                                Layer = 1,
                                SourcePosition = dummyBoard,
                                TargetPosition = TargetPosition.ToString(),
                                Orientation = 0,
                                Tasktype = 1,
                                TransferState = 0,
                                CreationDate = date,
                            };
                            t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);
                            layer = 2;
                        }
                        //根据material的类型及库存来确定需要从哪些位置取多少张坂
                        //foreach (var material in materials)
                        //{ }
                        //// 查看需要多少原材料
                        //if (material.Key.Contains("垫板"))
                        //    {
                        //        continue;
                        //    }
                        if (TargetPosition.ToString().Contains("Pre"))
                        {
                            //1.选择库内一个空位置
                            var PreStacked = Db.T_CCHS_Stock.FirstOrDefault(s => s.ActualQuantity == 0 && !s.Positioncode.Contains("feed"));
                            if (PreStacked == null)
                            {
                                //说明库内没有空位置，无法执行预叠板任务
                                return new Returnstructure() { Code = -1, Msg = LocalText.No_space };
                            }
                            else
                            {
                                //预叠板位置是
                                TargetPosition = PreStacked.Positioncode;
                                //预叠板的任务是需要倒叙的，将sourcePosition中的数据倒叙
                                // 将Dictionary转换为List
                                List<KeyValuePair<string, int>> list = sourcePosition.ToList();
                                // 对List进行倒序操作
                                list.Reverse();
                                // 将倒序后的List重新放回Dictionary
                                sourcePosition = list.ToDictionary(x => x.Key, x => x.Value);

                                stackInfoConstruct.stackDetails.Reverse();

                                layer = 1;

                                t_CCHS_JobList.TaskQuantity -= 1;
                                t_CCHS_JobList.TargetType = 3;
                            }

                        }
                        var position = string.Empty;
                        int aq = 0;
                        foreach (var item in stackInfoConstruct.stackDetails)
                        {
                            if (item.Material.Contains("垫板"))
                            {
                                continue;
                            }
                            //找到这个物料的库存位置 取一张 先计算剩余的物料是否满足
                            var positionInfo = Db.T_CCHS_Stock.Where(s => s.Material == item.Material).ToList();

                            if (positionInfo != null)
                            {
                                foreach (var item_pos in positionInfo)
                                {
                                    position = item_pos.Positioncode;
                                    aq = (int)item_pos.ActualQuantity;
                                    var tasks = Db.T_CCHS_TaskDetail.Where(s => s.SourcePosition == position && s.TransferState != 30).Count();
                                    if (tasks + 1 > aq)
                                    {
                                        return new Returnstructure() { Code = -1, Msg = item.Material + " - 库存不足" };
                                    }
                                    //生成任务
                                    t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                                    {
                                        JobId = stackInfoConstruct.stackInfo.JobId,
                                        StackId = stackInfoConstruct.stackInfo.StackId,
                                        StackType = 1,
                                        Material = stackInfoConstruct.stackDetails[layer - 1].Material,
                                        Boardcode = stackInfoConstruct.stackDetails[layer - 1].Boardcode,
                                        BoardType = 1,//原材料 2=余料
                                        Layer = layer++,
                                        SourcePosition = position,
                                        TargetPosition = TargetPosition.ToString(),
                                        Orientation = 0,
                                        Tasktype = 1,
                                        TransferState = 0,
                                        CreationDate = date,
                                    };
                                    t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);
                                    break;
                                }
                            }
                        }

                        goto CreateJob;

                        var stockInfo = Db.T_CCHS_Stock.ToList();//Where(s => s.Material.Equals(material.Key)).
                        var Pcs = stackInfoConstruct.stackDetails.Sum(s => s.BoardQuantity);//.Where(s => s.Material.Equals(material.Key))

                        //需要注释掉
                        foreach (var item in stockInfo)
                        {
                            if (item.ActualQuantity >= Pcs)
                            {
                                calculatedPcs = (int)Pcs;
                                sourcePosition.Add(item.Positioncode, calculatedPcs);
                                break;
                            }
                            else
                            {
                                if (sourcePosition.Values.Sum() + (int)item.ActualQuantity > Pcs)
                                {
                                    calculatedPcs = (int)Pcs - sourcePosition.Values.Sum();
                                    sourcePosition.Add(item.Positioncode, calculatedPcs);
                                }
                                else
                                {
                                    calculatedPcs = (int)item.ActualQuantity;
                                    sourcePosition.Add(item.Positioncode, (int)item.ActualQuantity);
                                }
                            }
                            Pcs -= calculatedPcs;
                        }

                        /*以下是源代码*/


                        //获取当前排序
                        var sortInfo = Db.T_CCHS_JobList.OrderByDescending(s => s.Sort).FirstOrDefault();
                        var sort = 0;
                        if (sortInfo == null)
                        {
                            sort = 0;
                        }
                        else
                        {
                            sort = (int)sortInfo.Sort;
                        }

                        //生成出库任务 Job
                        t_CCHS_JobList = new T_CCHS_JobList()
                        {
                            JobId = stackInfoConstruct.stackInfo.JobId,
                            StackId = stackInfoConstruct.stackInfo.StackId,
                            Material = "Rainbow",
                            JobType = 1,//出库任务
                            TargetType = 1,
                            TaskQuantity = stackInfoConstruct.stackDetails.Sum(s => s.BoardQuantity),
                            TargetPosition = TargetPosition.ToString(),
                            State = 10,
                            CreationDate = date,
                            Sort = sort + 1
                        };

                        //如果是出库任务到出库口
                        if (TargetPosition.ToString().Contains("Outfeed"))
                        {
                            var dummyBoard = Db.T_CCHS_Stock.FirstOrDefault(s => s.Material.Equals("垫板")).Positioncode;
                            //生成垫板任务 //1.找到垫板库存信息
                            t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                            {
                                JobId = stackInfoConstruct.stackInfo.JobId,
                                StackId = stackInfoConstruct.stackInfo.StackId,
                                StackType = 1,
                                Material = "垫板",
                                Boardcode = stackInfoConstruct.stackDetails[0].Boardcode,
                                BoardType = 0,//垫板
                                Layer = 1,
                                SourcePosition = dummyBoard,
                                TargetPosition = TargetPosition.ToString(),
                                Orientation = 0,
                                Tasktype = 1,
                                TransferState = 0,
                                CreationDate = date,
                            };
                            t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);
                        }
                        else//如果不是出料口，是预叠板任务
                        {
                            //1.选择库内一个空位置
                            var PreStacked = Db.T_CCHS_Stock.FirstOrDefault(s => s.ActualQuantity == 0 && !s.Positioncode.Contains("feed"));
                            if (PreStacked == null)
                            {
                                //说明库内没有空位置，无法执行预叠板任务
                                return new Returnstructure() { Code = -1, Msg = LocalText.No_space };
                            }
                            else
                            {
                                //预叠板位置是
                                TargetPosition = PreStacked.Positioncode;
                                //预叠板的任务是需要倒叙的，将sourcePosition中的数据倒叙
                                // 将Dictionary转换为List
                                List<KeyValuePair<string, int>> list = sourcePosition.ToList();
                                // 对List进行倒序操作
                                list.Reverse();
                                // 将倒序后的List重新放回Dictionary
                                sourcePosition = list.ToDictionary(x => x.Key, x => x.Value);

                                stackInfoConstruct.stackDetails.Reverse();

                                layer = 1;

                                t_CCHS_JobList.TaskQuantity -= 1;
                                t_CCHS_JobList.TargetType = 3;
                            }
                        }

                        //库存满足，生成任务，不锁定库位信息
                        for (int i = 0; i <= sourcePosition.Count() - 1; i++)
                        {
                            for (int j = 1; j <= (int)sourcePosition.Values.ToList()[i]; j++)
                            {
                                t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                                {
                                    JobId = stackInfoConstruct.stackInfo.JobId,
                                    StackId = stackInfoConstruct.stackInfo.StackId,
                                    StackType = 1,
                                    Material = stackInfoConstruct.stackDetails[layer - 1].Material,
                                    Boardcode = stackInfoConstruct.stackDetails[layer - 1].Boardcode,
                                    BoardType = 1,//原材料 2=余料
                                    Layer = layer,
                                    SourcePosition = sourcePosition.Keys.ToList()[i],
                                    TargetPosition = TargetPosition.ToString(),
                                    Orientation = stackInfoConstruct.stackDetails[i].Orientation,
                                    Tasktype = 1,
                                    TransferState = 0,
                                    CreationDate = date,
                                };
                                layer++;
                                t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);
                            }
                        }
                        goto CreateJob;
                    }

                CreateJob:

                    Db.T_CCHS_JobList.Add(t_CCHS_JobList);
                    Db.T_CCHS_TaskDetail.AddRange(t_CCHS_TaskDetails);
                    //满足上边的条件后即可生成出库任务
                    var DuplicateStackDatas = Db.T_CCHS_StackDetail.Where(s => s.JobId.Equals(stackInfoConstruct.stackInfo.JobId)
                                                                    && s.StackId.Equals(stackInfoConstruct.stackInfo.StackId)).ToList();
                    if (DuplicateStackDatas.Count > 0)
                    {
                        Db.T_CCHS_StackDetail.RemoveRange(DuplicateStackDatas);
                        var DuplicateData = Db.T_CCHS_StackInfo.Where(s => s.JobId.Equals(stackInfoConstruct.stackInfo.JobId)
                                                                        && s.StackId.Equals(stackInfoConstruct.stackInfo.StackId)).ToIList();
                        Db.T_CCHS_StackInfo.RemoveRange(DuplicateData);
                    }

                    foreach (var item in stackInfoConstruct.stackDetails)
                    {
                        list_Detail.Add(Handle_Common.Mapper(new T_CCHS_StackDetail(), item));
                    }
                    Db.T_CCHS_StackDetail.AddRange(list_Detail);
                    Db.T_CCHS_StackInfo.Add(Handle_Common.Mapper(new T_CCHS_StackInfo(), stackInfoConstruct.stackInfo));

                    return Db.SaveChanges() > 0 ? new Returnstructure() { Code = 1, Msg = LocalText.Congratulations }
                    : new Returnstructure() { Code = -1, Msg = LocalText.Add_failed };
                }
            }
            catch (Exception ex)
            {
                SerilogHandle.Logger_Modify.Error(ex.Message);
                return new Returnstructure() { Code = -99, Msg = Utility.GetLocalText("System abnormality") + ex.Message };
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="Material"></param>
        /// <param name="InfeedPos"></param>
        /// <param name="TargetPos"></param>
        /// <param name="Pcs"></param>
        /// <param name="Dummyboard"></param>
        /// <returns></returns>
        public Returnstructure ManuallyInfeed(string Material, string InfeedPos, string TargetPosition, int Pcs, bool Dummyboard = false)
        {
            try
            {
                DateTime dateTime = DateTime.Now;
                List<T_CCHS_TaskDetail> t_CCHS_TaskDetails = new List<T_CCHS_TaskDetail>();
                T_CCHS_TaskDetail t_CCHS_TaskDetail;
                using (Db_CCHS Db = new Db_CCHS())
                {
                    //如果当前有未完成的入库任务则不允许再次下发入库任务
                    var InfeedTaskCount = Db.T_CCHS_JobList.Where(s => s.JobType == 0 && s.State < 30).Count();
                    if (InfeedTaskCount > 0)
                    {
                        return new Returnstructure() { Code = -1, Msg = LocalText.Wait_job_done };
                    }
                    //判断要入库的位置上的material是否与要入库的相同。
                    var ExistMaterial = Db.T_CCHS_Stock.FirstOrDefault(s => s.Positioncode.Equals(TargetPosition)).Material;
                    if (!string.IsNullOrWhiteSpace(ExistMaterial) && !ExistMaterial.Equals(Material))
                    {
                        return new Returnstructure() { Code = -1, Msg = LocalText.Different_materials };
                    }

                    //判断要入库的加上已在库内的数量是否超限
                    var ExistQuantity = Db.T_CCHS_Stock.FirstOrDefault(s => s.Positioncode.Equals(TargetPosition)).ActualQuantity;
                    if ((ExistQuantity + Pcs) > 108)
                    {
                        return new Returnstructure() { Code = -1, Msg = LocalText.Exceeds_the_limit };
                    }
                    var JobId = "MI_" + dateTime.ToString("yyyyMMddhhssfff");
                    if (Dummyboard)
                    {
                        //生成垫板任务 //1.找到垫板库存信息
                        t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                        {
                            JobId = JobId,
                            StackId = Material + "_" + dateTime.ToString("yyyyMMddHHmmssfff"),
                            StackType = 1,
                            Material = "垫板",
                            Boardcode = "DB_18",
                            BoardType = 0,
                            Layer = 0,
                            TargetPosition = TargetPosition.ToString(),
                            Orientation = 0,
                            Tasktype = 1,
                            TransferState = 0,
                            CreationDate = dateTime,
                        };
                        t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);
                    }

                    var sort = 1;
                    var jobInfo = Db.T_CCHS_JobList.OrderByDescending(s => s.Sort).FirstOrDefault();
                    if (jobInfo != null)
                    {
                        sort = (int)jobInfo.Sort + 1;
                    }

                    T_CCHS_JobList t_CCHS_JobList = new T_CCHS_JobList()
                    {
                        JobId = JobId,
                        StackId = Material + "_" + dateTime.ToString("yyyyMMddHHmmssfff"),
                        Material = Material,
                        JobType = 0,
                        TargetType = 0,
                        TargetPosition = TargetPosition,
                        TaskQuantity = Pcs + 1,
                        Sort = sort,
                        State = 10,
                        CreationDate = dateTime,
                    };

                    Db.T_CCHS_JobList.Add(t_CCHS_JobList);
                    var boardcode = Db.T_CCHS_Boardlibrary.FirstOrDefault(s => s.Material.Equals(Material)).Boardcode;
                    for (int i = 1; i <= Pcs; i++)
                    {
                        t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                        {
                            JobId = JobId,
                            StackId = Material + "_" + dateTime.ToString("yyyyMMddHHmmssfff"),
                            StackType = 1,
                            Material = Material,
                            Boardcode = boardcode,
                            BoardType = 1,//垫板
                            Layer = i,
                            SourcePosition = InfeedPos,
                            TargetPosition = TargetPosition.ToString(),
                            Orientation = 0,
                            Tasktype = 0,
                            TransferState = 0,
                            CreationDate = dateTime,
                        };
                        t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);
                    }
                    var Last_dummyboardTarget = "";
                    //找到库内的垫板堆垛，没有的话找一个空堆垛
                    var dummyboardInfo = Db.T_CCHS_Stock.OrderBy(s => s.ActualQuantity).FirstOrDefault(s => s.Material.Equals("垫板"));

                    if (dummyboardInfo != null && dummyboardInfo.ActualQuantity < 108)//60库内板材叠放最低层数  ? 或者是通过高度计算
                    {
                        Last_dummyboardTarget = dummyboardInfo.Positioncode;
                    }
                    else
                    {
                        //说明都是满垛的，找一个空位置
                        Last_dummyboardTarget =
                                                Db.T_CCHS_Stock.OrderBy(s => s.Positioncode)
                                                .FirstOrDefault(s => s.ActualQuantity == 0
                                                && s.Positioncode != TargetPosition
                                                && s.Positioncode != InfeedPos).Positioncode;
                    }

                    //生成入库时最后一张垫板任务
                    t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                    {
                        JobId = JobId,
                        StackId = Material + "_" + dateTime.ToString("yyyyMMddHHmmssfff"),
                        StackType = 1,
                        Material = "垫板",
                        Boardcode = "DB_18",
                        BoardType = 0,//垫板
                        Layer = Pcs + 1,
                        SourcePosition = InfeedPos,
                        TargetPosition = Last_dummyboardTarget,
                        Orientation = 0,
                        Tasktype = 0,
                        TransferState = 0,
                        CreationDate = dateTime,
                    };
                    t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);

                    Db.T_CCHS_TaskDetail.AddRange(t_CCHS_TaskDetails);

                    //将信息写入库存Infeed位置  
                    var o_StockInfo = Db.T_CCHS_Stock.FirstOrDefault(s => s.Positioncode.Equals(InfeedPos));

                    o_StockInfo.Positioncode = InfeedPos;
                    o_StockInfo.StackId = Material + "_" + dateTime.ToString("yyyyMMddHHmmssfff");
                    o_StockInfo.Material = Material;
                    o_StockInfo.ActualQuantity = Pcs + 1;
                    o_StockInfo.ActualHight = 0;
                    o_StockInfo.VirtualQuantity = Pcs + 1;
                    o_StockInfo.VirtualHight = 0;
                    o_StockInfo.State = 0;
                    o_StockInfo.CreationDate = dateTime;

                    T_CCHS_StockDetail t_CCHS_StockDetail;
                    List<T_CCHS_StockDetail> t_CCHS_StockDetails = new List<T_CCHS_StockDetail>();
                    for (int i = 1; i <= Pcs + 1; i++)
                    {
                        t_CCHS_StockDetail = new T_CCHS_StockDetail()
                        {
                            Positioncode = InfeedPos,
                            StackId = Material + "_" + dateTime.ToString("yyyyMMddHHmmssfff"),
                            Material = Material,
                            Boardcode = boardcode,
                            Layer = i,
                            State = 0,
                            CreationDate = dateTime,
                        };
                        t_CCHS_StockDetails.Add(t_CCHS_StockDetail);
                    }

                    Db.T_CCHS_StockDetail.AddRange(t_CCHS_StockDetails);

                    return Db.SaveChanges() > 0 ? new Returnstructure() { Code = 1, Msg = LocalText.Congratulations }
                    : new Returnstructure() { Code = -1, Msg = LocalText.Add_failed };
                }
            }
            catch (Exception ex)
            {
                return new Returnstructure() { Code = 99, Msg = ex.Message };
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Material"></param>
        /// <param name="TargetPos"></param>
        /// <param name="Pcs"></param>
        /// <param name="Dummyboard"></param>
        /// <returns></returns>
        public Returnstructure ManuallyOutfeed(string Material, string OutfeedPos, string TargetPosition, int Pcs, bool Dummyboard = true)
        {
            try
            {
                DateTime dateTime = DateTime.Now;
                List<T_CCHS_TaskDetail> t_CCHS_TaskDetails = new List<T_CCHS_TaskDetail>();
                T_CCHS_TaskDetail t_CCHS_TaskDetail;
                using (Db_CCHS Db = new Db_CCHS())
                {
                    var stockInfo = Db.T_CCHS_Stock.Where(s => s.Material.Equals(Material) && !s.Positioncode.Contains("feed")).OrderBy(s => s.ActualQuantity);
                    //判断要出库的数量是否超限
                    var ExistQuantity = stockInfo.Sum(s => s.ActualQuantity);
                    if (ExistQuantity < Pcs)
                    {
                        return new Returnstructure() { Code = -1, Msg = LocalText.Exceeds_the_limit };
                    }

                    var First_dummyboard = "";

                    var dummyboardInfo = Db.T_CCHS_Stock.OrderBy(s => s.ActualQuantity).FirstOrDefault(s => s.Material.Equals("垫板"));

                    if (dummyboardInfo != null)
                    {
                        First_dummyboard = dummyboardInfo.Positioncode;
                    }
                    else
                    {
                        return new Returnstructure() { Code = -1, Msg = LocalText.Empty_DummyBoard };
                    }

                    var sourcePosition = new Dictionary<string, int>();
                    int calculatedPcs = 0;
                    if (OutfeedPos.Equals(Utility.GetLocalText("System allocated")))
                    {
                        foreach (var item in stockInfo)
                        {
                            if (item.ActualQuantity >= Pcs)
                            {
                                calculatedPcs = Pcs;
                                sourcePosition.Add(item.Positioncode, calculatedPcs);
                                break;
                            }
                            else
                            {
                                if (sourcePosition.Values.Sum() + (int)item.ActualQuantity > Pcs)
                                {
                                    calculatedPcs = Pcs - sourcePosition.Values.Sum();
                                    sourcePosition.Add(item.Positioncode, calculatedPcs);
                                }
                                else
                                {
                                    calculatedPcs = (int)item.ActualQuantity;
                                    sourcePosition.Add(item.Positioncode, (int)item.ActualQuantity);
                                }
                            }
                            Pcs -= calculatedPcs;
                        }
                    }
                    else//主动选择的
                    {
                        //获取当前位置的数量信息与PCS比对
                        var currentStock = Db.T_CCHS_Stock.FirstOrDefault(s => s.Positioncode == OutfeedPos);
                        if (!currentStock.Material.Equals(Material))
                        {
                            return new Returnstructure() { Code = -1, Msg = LocalText.Different_materials };
                        }
                        if (currentStock.ActualQuantity >= Pcs)
                        {
                            sourcePosition.Add(OutfeedPos, Pcs);
                        }
                        else
                        {
                            return new Returnstructure() { Code = -1, Msg = LocalText.Out_of_stock };
                        }
                    }


                    var JobId = "MO_" + dateTime.ToString("yyyyMMddhhssfff");
                    var sort = 1;
                    var jobInfo = Db.T_CCHS_JobList.OrderByDescending(s => s.Sort).FirstOrDefault();
                    if (jobInfo != null)
                    {
                        sort = (int)jobInfo.Sort + 1;
                    }

                    T_CCHS_JobList t_CCHS_JobList = new T_CCHS_JobList()
                    {
                        JobId = JobId,
                        StackId = Material + "_" + dateTime.ToString("yyyyMMddHHmmssfff"),
                        Material = Material,
                        JobType = 1,
                        TargetType = 0,
                        TargetPosition = TargetPosition,
                        TaskQuantity = sourcePosition.Values.Sum() + 1,
                        Sort = sort,
                        State = 10,
                        CreationDate = dateTime,
                    };
                    Db.T_CCHS_JobList.Add(t_CCHS_JobList);

                    if (Dummyboard)
                    {
                        t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                        {
                            JobId = JobId,
                            StackId = Material + "_" + dateTime.ToString("yyyyMMddHHmmssfff"),
                            StackType = 1,
                            Material = "垫板",
                            Boardcode = "DB_18",
                            BoardType = 0,
                            Layer = 1,
                            SourcePosition = First_dummyboard,
                            TargetPosition = TargetPosition.ToString(),
                            Orientation = 0,
                            Tasktype = 1,
                            TransferState = 0,
                            CreationDate = dateTime,
                        };
                        t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);
                    }

                    //int outLayer = 2;
                    var boardcode = Db.T_CCHS_Boardlibrary.FirstOrDefault(s => s.Material.Equals(Material)).Boardcode;

                    foreach (var item in sourcePosition)
                    {
                        for (int i = 1; i <= item.Value; i++)
                        {
                            t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                            {
                                JobId = JobId,
                                StackId = Material + "_" + dateTime.ToString("yyyyMMddHHmmssfff"),
                                StackType = 1,
                                Material = Material,
                                Boardcode = boardcode,
                                BoardType = 1,
                                Layer = Dummyboard ? i + 1 : i,
                                SourcePosition = item.Key,
                                TargetPosition = TargetPosition.ToString(),
                                Orientation = 0,
                                Tasktype = 1,
                                TransferState = 0,
                                CreationDate = dateTime,
                            };
                            //outLayer++;
                            t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);
                        }

                        Db.T_CCHS_TaskDetail.AddRange(t_CCHS_TaskDetails);
                        //将下达后的出库任务的虚拟库存扣除，避免下达超出库存容量的出库任务
                        var o_sourcePosition = stockInfo.FirstOrDefault(s => s.Positioncode == item.Key);
                        o_sourcePosition.VirtualQuantity -= item.Value;
                    }

                    return Db.SaveChanges() > 0 ? new Returnstructure() { Code = 1, Msg = LocalText.Congratulations }
                    : new Returnstructure() { Code = -1, Msg = LocalText.Add_failed };
                }
            }
            catch (Exception ex)
            {
                return new Returnstructure() { Code = 99, Msg = ex.Message };
            }
        }

        public void Return2Warehouse()
        {
            try
            {
                DateTime dateTime = DateTime.Now;
                List<T_CCHS_TaskDetail> t_CCHS_TaskDetails = new List<T_CCHS_TaskDetail>();
                using (Db_CCHS Db = new Db_CCHS())
                {
                    var StockInfo = Db.T_CCHS_StockDetail.Where(s => s.Positioncode == "Outfeed01").ToList();
                    if (StockInfo == null)
                    {
                        return;
                    }
                    StockInfo.Reverse();

                    //获取当前排序
                    var sortInfo = Db.T_CCHS_JobList.OrderByDescending(s => s.Sort).FirstOrDefault();
                    var sort = 0;
                    if (sortInfo == null)
                    {
                        sort = 0;
                    }
                    else
                    {
                        sort = (int)sortInfo.Sort;
                    }

                    T_CCHS_JobList t_CCHS_JobList = new T_CCHS_JobList()
                    {
                        JobId = "Re-" + dateTime.ToString("yyyyMMddHHmmssfff"),
                        StackId = "Rainbow" + dateTime.ToString("yyyyMMddHHmmssfff"),
                        Material = "Rainbow",
                        JobType = 0,
                        TargetType = 0,
                        TargetPosition = "Rainbow",
                        TaskQuantity = StockInfo.Count(),
                        Sort = sort,
                        State = 10,
                        CreationDate = dateTime,
                    };

                    Db.T_CCHS_JobList.Add(t_CCHS_JobList);
                    int i = 1;
                    foreach (var item in StockInfo)
                    {
                        var boardcode = Db.T_CCHS_Boardlibrary.FirstOrDefault(s => s.Material == item.Material).Boardcode;
                        var targetPosition = string.Empty;
                        var targetInfo = Db.T_CCHS_Stock.OrderBy(s => s.ActualQuantity).FirstOrDefault(s => s.Material == item.Material && s.Positioncode != "Outfeed01");
                        if (targetInfo == null)
                        {
                            //库内没有这个物料了，证明有一个空位置，找到这个空位置
                            targetPosition = Db.T_CCHS_Stock.FirstOrDefault(s => s.ActualQuantity == 0).Positioncode;
                        }
                        else
                        {
                            targetPosition = targetInfo.Positioncode;
                        }
                        T_CCHS_TaskDetail t_CCHS_TaskDetail = new T_CCHS_TaskDetail()
                        {
                            JobId = t_CCHS_JobList.JobId,
                            StackId = t_CCHS_JobList.StackId,
                            StackType = 1,
                            Material = item.Material,
                            Boardcode = boardcode,
                            BoardType = 1,
                            Layer = i++,
                            SourcePosition = "Outfeed01",
                            TargetPosition = targetPosition,
                            Orientation = 0,
                            Tasktype = 0,
                            TransferState = 0,
                            CreationDate = dateTime,
                        };
                        t_CCHS_TaskDetails.Add(t_CCHS_TaskDetail);
                    }
                    Db.T_CCHS_TaskDetail.AddRange(t_CCHS_TaskDetails);
                    Db.SaveChanges();
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}